//
//  StrangeThingViewController.m
//  MyLittleBrother
//
//  Created by speeda on 17/7/31.
//  Copyright © 2017年 speeda. All rights reserved.
//

#import "StrangeThingViewController.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>
#import "TZImagePickerController.h"
#import "OSSImageUploader.h"
#import "ACMediaFrame.h"
#import "UITextView+YZEmotion.h"
#import "YZTextAttachment.h"

static NSString *const AccessKey = @"LTAIOeyjfgCpgPv2";
static NSString *const SecretKey = @"4cQA2kOOuPhmTaO9wFQ4kMnR90smtk";
static NSString *const BucketName = @"speeda-img";
static NSString *const AliYunHost = @"https://oss-cn-hangzhou.aliyuncs.com";

@interface StrangeThingViewController () <UITextViewDelegate>


@property (weak, nonatomic) IBOutlet UITextView *editTextView;

@property (nonatomic, copy) NSString *resultImgUrl;
@property (nonatomic, strong) NSMutableArray *resultImgUrlArray;

@property(nonatomic, strong) OSSClient *client;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topicButtonHeight;
@property (weak, nonatomic) IBOutlet UIButton *topicButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) YZEmotionKeyboard *emotionKeyboard;

@end

@implementation StrangeThingViewController

static NSString *cellID = @"imgCollectionView";

// 懒加载键盘
- (YZEmotionKeyboard *)emotionKeyboard
{
    // 创建表情键盘
    if (_emotionKeyboard == nil) {
        __weak typeof(self) weakSelf = self;
        YZEmotionKeyboard *emotionKeyboard = [YZEmotionKeyboard emotionKeyboard];
        emotionKeyboard.sendContent = ^(NSString *content){
            // 点击发送会调用，自动把文本框内容返回给你

            [weakSelf.editTextView resignFirstResponder];

        };
        
        _emotionKeyboard = emotionKeyboard;
    }
    return _emotionKeyboard;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavigationItem];
    
    [self initView];
    
    [self initTableView];
    
}


- (void)setNavigationItem {
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(rightBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [rightBtn sizeToFit];
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
    
}


- (void)initView {

    UIView *toolbarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    toolbarView.backgroundColor = [UIColor whiteColor];
    toolbarView.layer.borderWidth = 1;
    toolbarView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    UIButton *toolbarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    toolbarButton.frame = CGRectMake(20, 10, 20, 20);
    [toolbarButton setImage:[UIImage imageNamed:@"smail"] forState:UIControlStateNormal];
    [toolbarButton addTarget:self action:@selector(toolbarBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [toolbarView addSubview:toolbarButton];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.editTextView.delegate = self;
    self.editTextView.inputAccessoryView = toolbarView;
    
    if (self.topicString != nil) {
        
        self.topicButton.layer.cornerRadius = 15;
        [self.topicButton setTitle:[NSString stringWithFormat:@" #%@# ",self.topicString] forState:UIControlStateNormal];
    } else {
        
        self.topicButtonHeight.constant = 0;
    }
}

- (void)initTableView {
    

    self.tableView.tableFooterView = [[UIView alloc] init];
    UIView *headerView = [[UIView alloc] init];
    
    ACSelectMediaView *mediaView = [[ACSelectMediaView alloc] initWithFrame:CGRectMake(10,10, SCREEN_WIDTH - 20, 2 * (SCREEN_WIDTH - 20) + 40)];
    mediaView.allowPickingVideo = YES;
    NSMutableArray *imgs = [NSMutableArray array];
    [mediaView observeSelectedMediaArray:^(NSArray<ACMediaModel *> *list) {
        // do something
        for (ACMediaModel *model in list) {
            //遍历得到模型中想要的数据  e.g.
            // id uplodaType = model.uploadType;
            // NSString *name = model.name;
            
            [imgs addObject:model.image];
            
        }
        [OSSImageUploader asyncUploadImages:imgs complete:^(NSArray<NSString *> *names, UploadImageState state) {
            
            NSString *strUrl = [AliYunHost stringByReplacingOccurrencesOfString:@"https://" withString:@""];
            for (NSString *name in names) {
                NSString *urlSt = [NSString stringWithFormat:@"https://%@.%@/%@",BucketName,strUrl,name];
                
                [self.resultImgUrlArray addObject:urlSt];
            }
            
        }];
        
    }];
    [headerView addSubview:mediaView];
    
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetMaxY(mediaView.frame));
    self.tableView.tableHeaderView = headerView;
}


- (void)toolbarBtnAction:(UIButton *)sender {

    if (_editTextView.inputView == nil) {
        _editTextView.yz_emotionKeyboard = self.emotionKeyboard;
        [sender setImage:[UIImage imageNamed:@"toolbar-text"] forState:UIControlStateNormal];
    } else {
        _editTextView.inputView = nil;
        [_editTextView reloadInputViews];
        [sender setImage:[UIImage imageNamed:@"smail"] forState:UIControlStateNormal];
    }
}


#pragma mark -- 发布
- (void)rightBtnItemAction {
    
    self.resultImgUrl = nil;
    
    for (NSString *string in self.resultImgUrlArray ) {
        
        if (self.resultImgUrl != NULL) {
            
            self.resultImgUrl = [NSString stringWithFormat:@"%@|%@",self.resultImgUrl,string];
            
        } else {
            
            self.resultImgUrl = string;
        }
    }

    [self requestGetcode];
}



#pragma mark -- 标签按钮
- (IBAction)tagBtnAction:(id)sender {
    
    
}


#pragma mark -- 发贴
- (void)requestGetcode {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    dict[@"command"] = @"circle";
    dict[@"userid"] = userId;
    dict[@"topicid"] = self.topicid;
    dict[@"article"] = [self emotionText];
    dict[@"imgs"] = self.resultImgUrl;
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
            
            NSLog(@"发贴 = %@",responseObject);
            [self.navigationController popViewControllerAnimated:YES];
            
        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


#pragma mark -- UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {

    if ([textView.text isEqualToString:@"分享您的新鲜事吧......"]) {
        textView.textColor = [UIColor blackColor];
        textView.text = @"";
    }
}

//- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    
//    if ([text isEqualToString:@"\n"]) {
//        
//        [textView resignFirstResponder];
//        
//        return NO;
//    }
//    
//    return YES;
//}

// 获取表情字符串
- (NSString *)emotionText
{
    
    NSMutableString *strM = [NSMutableString string];
    
    [_editTextView.attributedText enumerateAttributesInRange:NSMakeRange(0, _editTextView.attributedText.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        NSString *str = nil;
        
        YZTextAttachment *attachment = attrs[@"NSAttachment"];
        
        if (attachment) { // 表情
            str = attachment.emotionStr;
            [strM appendString:str];
        } else { // 文字
            str = [_editTextView.attributedText.string substringWithRange:range];
            [strM appendString:str];
        }
        
    }];
    return strM;
}


- (NSMutableArray *)resultImgUrlArray {
    
    if (!_resultImgUrlArray) {
        _resultImgUrlArray = [NSMutableArray array];
    }
    
    return _resultImgUrlArray;
}


@end
